/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.fatecpg.ads.es3.tp.persistence;

import java.awt.Component;
import java.io.*;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 *
 * @author Felipe
 */
public class Backup {


    public void setBackup(JPanel panel, String arquivo) throws IOException {
        
        File arq = new File("backup\\"+arquivo);

        arq.delete();
        
        for (Component c : panel.getComponents()) {
            if (c instanceof JTextField) {
                JTextField tx = (JTextField) c;
                String valor = tx.getText();
                try {
                    arq.createNewFile();


            FileWriter fileWriter = new FileWriter(arq, true);



            PrintWriter printWriter = new PrintWriter(fileWriter);



            printWriter.println(valor);



            printWriter.flush();

            printWriter.close();;

                } catch (IOException error) {
                    JOptionPane.showMessageDialog(null, "Não foi possível efetuar o backup do dado: " + valor);
                }
            }
        }

    }

    public void getBackup(JPanel panel, String arquivo, int vect) throws IOException {
        try {
            
             //Chamando a classe que abre os arquivos
            FileReader i = new FileReader("backup\\"+arquivo);
            BufferedReader in = new BufferedReader(i);
            int ind = 0;
            String Linha = null;
            String v[] = new String[vect];
            //Lendo os dados do arquivo txt
            while ((Linha = in.readLine()) != null) {
                v[ind++] = Linha;
            }

            // fechando
            i.close();
            
            ind = 0;

            for (Component c : panel.getComponents()) {
                if (c instanceof JTextField) {
                    JTextField tx = (JTextField) c;
                    tx.setText(v[ind++]);

                }
            }

        } catch (Exception x) {
            x.printStackTrace();

        }


    }
}
